<?php

namespace Yjius\aibigmodel\doubao;

use Yjius\aibigmodel\AIBigModelBuilderInterface;
use Yjius\common\LoggerHelper;

class DouBao implements AIBigModelBuilderInterface
{
    //实例化代码
    static private $instance;

    private function __construct($params)
    {
        $this->chatUrl = $params['chat_url'] ?? "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
        $this->chatModel = $params['chat_model'] ?? "ep-20241210170055-7pb9m";//DB_PRO_32K
        $this->apiKey = $params['api_key'] ?? "";
        if (empty($this->apiKey)) {
            throw new \Exception("DouBao:api_key不能为空");
        }
        $this->saveLog = $params['save_log'] ?? false;
        if ($this->saveLog) {
            $this->loggerInstance = LoggerHelper::init();
        }
    }

    private function __clone()
    {
    }

    //单例模式
    static public function getInstance($params)
    {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self($params);
        }
        return self::$instance;
    }

    function chatOnce(array $paramsArray, array $customerParams)
    {
        $data = [
            'messages' => [
                [
                    'content' => 'You are a helpful assistant.',
                    'role' => 'system'
                ],
                [
                    'content' => "Hi",
                    'role' => 'user'
                ]
            ],
            'model' => $this->chatModel,
            'max_tokens' => 2048,
            'presence_penalty' => 0,
        ];
        $data = array_merge($data, $paramsArray);
        $res = $this->curlRequest($data);
        if ($this->saveLog) {
            //问题结果日志记录
            $this->loggerInstance->write("doubao_" . $this->apiKey . ".log", json_encode($data, JSON_UNESCAPED_UNICODE));
            $this->loggerInstance->write("doubao_" . $this->apiKey . ".log", $res);
        }
        return $res;
    }

    function chatOnceDealResult(string $paramsStr, array $customerParams)
    {
        try {
            // 将JSON字符串转换为关联数组
            $dataArr = json_decode($paramsStr, true);

            // 提取并返回聊天内容
            return $dataArr['choices'][0]['message']['content'] ?? "";
        } catch (\Exception $e) {
            // 直接返回null，不记录错误信息
            return null;
        }
    }

    //发起CURL请求
    private function curlRequest($data = [])
    {
        // 若没有配置环境变量，请用百炼API Key将下行替换为：$apiKey = "sk-xxx";
        // 设置请求头
        $headers = [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json'
        ];

        // 初始化cURL会话
        $ch = curl_init();
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $this->chatUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


        // 执行cURL会话
        $response = curl_exec($ch);

        // 检查是否有错误发生
        $errno = curl_errno($ch);       //curl错误码
        $error = curl_error($ch);       //curl错误信息

        if ($errno) {         //curl异常
            $curlError = json_encode(['curl_errno' => $errno, 'curl_error' => $error], JSON_UNESCAPED_UNICODE);
            throw new \Exception("curl异常：" . $curlError);
        }
        // 关闭cURL资源
        curl_close($ch);
        // 关闭cURL资源
        return $response;
    }

}